
package com.bytecodes.eaulas.mantenimiento;

import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.rmi.RemoteException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;

import com.bytecodes.eaulas.beans.Aula;
import com.bytecodes.eaulas.beans.Rol;
import com.bytecodes.eaulas.beans.Usuario;
import com.bytecodes.eaulas.comun.EAulasTableModel;
import com.bytecodes.eaulas.comun.Utils;
import com.bytecodes.eaulas.comun.servicios.EAulasServiciosImpl;
import com.bytecodes.eaulas.comun.servicios.EAulasServiciosInterface;
import com.bytecodes.eaulas.comun.servicios.TDSLanguageUtils;

/**
 * @author David David
 */
public class PanelBuscarUsuario extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 5377286001286654067L;
	private String idUsuarioCreador=null;
	private EAulasServiciosInterface servicios ;
	public PanelBuscarUsuario(String idUsuarioCreador) {
		this.idUsuarioCreador=idUsuarioCreador;
		try {
			servicios = new EAulasServiciosImpl();
		} catch (RemoteException exception) {
			exception.printStackTrace();
		}
		initComponents();
		Utils.clearPanel(this);
	}

	private void buttonBuscarActionPerformed(ActionEvent e) {
		String dni =this.textFieldDNI.getText();
		String nombre = this.textNombre.getText();
		try {
			String filtro = "";
			Boolean where= false;
			if(!"".equals(dni)){
				 filtro = " WHERE userid like '%"+dni+"%'"; 
				 where=true;
			}
			if(!"".equals(nombre)){
				if(where)
					filtro += " AND name like '%"+nombre+"%'"; 
				else
					filtro =" WHERE name like '%"+nombre+"%'"; 
			}
			 tableModel= servicios.getTableModel("users", filtro);
			 tableModel.fireTableDataChanged();
			 tableUsuarios.setModel(tableModel);
		} catch (RemoteException exception) {
			System.out.println("Error buscando");
			System.out.println(exception.getMessage());
		}
	}
	
	private void buttonBorrarActionPerformed(ActionEvent e) {
		Utils.clearPanel(this);
	}
	
	private void buttonActualizarActionPerformed(ActionEvent e) {
		Usuario usuario= new Usuario();
		if(actualizarUsuario(usuario)){
			try {
				int result = JOptionPane.showConfirmDialog(null, TDSLanguageUtils.getMessage("panelGestionUsuarios.modificar.pregunta"),
						 TDSLanguageUtils.getMessage("panelGestionUsuarios.modificar"), JOptionPane.OK_CANCEL_OPTION);
				if(result==0){
					servicios.updateUsuario(usuario, idUsuarioCreador);
					Utils.mostraMensajeInformacion( TDSLanguageUtils.getMessage("panelGestionUsuarios.modificar.ok"), TDSLanguageUtils.getMessage("panelGestionUsuarios.modificar"));
					Utils.clearPanel(this);
					tableModel= servicios.getTableModel("users", " where inactivation_date is null");
					tableModel.fireTableDataChanged();
					tableUsuarios.setModel(tableModel);
				}
			} catch (RemoteException exception) {
				exception.printStackTrace();
			}
			
		}
		else{
			Utils.mostraMensajeError(TDSLanguageUtils.getMessage("panelGestionUsuarios.datos.numericos"), TDSLanguageUtils.getMessage("panelGestionUsuarios.modificar"));
		}
	}

	private boolean actualizarUsuario(Usuario usuario) {
		boolean ok=true;
		if((!Utils.isNumeric(textFieldCodigoPostal.getText()))||(!Utils.isNumeric(textFieldTelefono.getText()))||(!Utils.isNumeric(textFieldTelefonoMovil.getText()))){
			ok=false;
		}
		if(!"".equals(textFieldDNI.getText()))
				usuario.setCodUsuario(textFieldDNI.getText());
		if(!"".equals(textApellido1.getText()))
			usuario.setApellido1(textApellido1.getText());
		if(!"".equals(textFieldApellido2.getText()))
			usuario.setApellido2(textFieldApellido2.getText());
		if(!"".equals(textFieldCodigoPostal.getText())&&(Utils.isNumeric(textFieldCodigoPostal.getText())))
			usuario.setCodPostal((textFieldCodigoPostal.getText()));
		if(!"".equals(textFieldCompania.getText()))
			usuario.setCompania((textFieldCompania.getText()));
		if(!"".equals(textFieldDireccion.getText()))
			usuario.setDireccion(textFieldDireccion.getText());
		if(!"".equals(textFieldEmail.getText()))
			usuario.setEmail(textFieldEmail.getText());
		if(!"".equals(textFieldTelefono.getText())&&(Utils.isNumeric(textFieldTelefono.getText())))
			usuario.setTelefono(textFieldTelefono.getText());
		if(!"".equals(textFieldTelefonoMovil.getText())&&(Utils.isNumeric(textFieldTelefonoMovil.getText())))
			usuario.setTelfMovil(textFieldTelefonoMovil.getText());
		if(!"".equals(textNombre.getText()))
			usuario.setNombre(textNombre.getText());
		if(!"".equals(textFieldCiudad.getText()))
			usuario.setLocalidad(textFieldCiudad.getText());
		return ok;
	}

	private void initComponents() {
		textNombre = new JTextField();
		textApellido1 = new JTextField();
		label1 = new JLabel();
		label2 = new JLabel();
		textFieldApellido2 = new JTextField();
		label3 = new JLabel();
		textFieldDNI = new JTextField();
		label4 = new JLabel();
		textFieldCompania = new JTextField();
		label5 = new JLabel();
		textFieldDireccion = new JTextField();
		label6 = new JLabel();
		textFieldCodigoPostal = new JTextField();
		label7 = new JLabel();
		textFieldCiudad = new JTextField();
		label8 = new JLabel();
		textFieldTelefono = new JTextField();
		label9 = new JLabel();
		textFieldTelefonoMovil = new JTextField();
		label10 = new JLabel();
		comboRol = new JComboBox();
		rellenarComboRoles(comboRol);
		label11 = new JLabel();
		textFieldEmail = new JTextField();
		scrollPane1 = new JScrollPane();
		tableUsuarios = new JTable();
		buttonBuscar = new JButton();
		buttonBorrar = new JButton();
		buttonActualizar = new JButton();
		textPassword= new JPasswordField();
		labelPass = new JLabel();
		
		try {
			tableModel= servicios.getTableModel("users", " where inactivation_date is null");
		} catch (RemoteException exception1) {
			exception1.printStackTrace();
		}
		tableUsuarios = new JTable(tableModel);
		tableUsuarios.addMouseListener(new MouseAdapter() 
		   {
		      public void mouseClicked(MouseEvent e) 
		      {
		         int fila = tableUsuarios.rowAtPoint(e.getPoint());
		         rellenarDatos( fila );
		      }

			
		   });

		//======== this ========

		setLayout(null);
		add(textNombre);
		textNombre.setBounds(110, 55, 130, textNombre.getPreferredSize().height);
		add(textApellido1);
		textApellido1.setBounds(110, 95, 185, 22);

		//---- label1 ----
		label1.setText(TDSLanguageUtils.getMessage("panelGestionUsuarios.lblnombre"));
		add(label1);
		label1.setBounds(20, 60, label1.getPreferredSize().width, 15);

		//---- label2 ----
		label2.setText(TDSLanguageUtils.getMessage("panelGestionUsuarios.lblape"));
		add(label2);
		label2.setBounds(20, 100, label2.getPreferredSize().width, 15);
		add(textFieldApellido2);
		textFieldApellido2.setBounds(350, 95, 165, 22);

		//---- label3 ----
		label3.setText(TDSLanguageUtils.getMessage("panelGestionUsuarios.lbldni"));
		add(label3);
		label3.setBounds(new Rectangle(new Point(20, 20), label3.getPreferredSize()));
		add(textFieldDNI);
		textFieldDNI.setBounds(110, 15, 130, textFieldDNI.getPreferredSize().height);

		//---- label4 ----
		label4.setText(TDSLanguageUtils.getMessage("panelGestionUsuarios.lblcompania"));
		add(label4);
		label4.setBounds(20, 145, label4.getPreferredSize().width, 15);
		add(textFieldCompania);
		textFieldCompania.setBounds(110, 145, 135, textFieldCompania.getPreferredSize().height);

		//---- label5 ----
		label5.setText(TDSLanguageUtils.getMessage("panelGestionUsuarios.lbldir"));
		add(label5);
		label5.setBounds(20, 200, label5.getPreferredSize().width, 15);
		add(textFieldDireccion);
		textFieldDireccion.setBounds(110, 200, 385, textFieldDireccion.getPreferredSize().height);

		//---- label6 ----
		label6.setText(TDSLanguageUtils.getMessage("panelGestionUsuarios.lblcodpostal"));
		add(label6);
		label6.setBounds(20, 255, label6.getPreferredSize().width, 15);
		add(textFieldCodigoPostal);
		textFieldCodigoPostal.setBounds(110, 250, 85, textFieldCodigoPostal.getPreferredSize().height);

		//---- label7 ----
		label7.setText(TDSLanguageUtils.getMessage("panelGestionUsuarios.lbllocalidad"));
		add(label7);
		label7.setBounds(new Rectangle(new Point(280, 255), label7.getPreferredSize()));
		add(textFieldCiudad);
		textFieldCiudad.setBounds(350, 255, 90, textFieldCiudad.getPreferredSize().height);

		//---- label8 ----
		label8.setText(TDSLanguageUtils.getMessage("panelGestionUsuarios.lbltelefono"));
		add(label8);
		label8.setBounds(20, 305, label8.getPreferredSize().width, 15);
		add(textFieldTelefono);
		textFieldTelefono.setBounds(110, 305, 110, textFieldTelefono.getPreferredSize().height);

		//---- label9 ----
		label9.setText(TDSLanguageUtils.getMessage("panelGestionUsuarios.lbltelefonomovil"));
		add(label9);
		label9.setBounds(new Rectangle(new Point(265, 310), label9.getPreferredSize()));
		add(textFieldTelefonoMovil);
		textFieldTelefonoMovil.setBounds(350, 310, 85, textFieldTelefonoMovil.getPreferredSize().height);

		//---- label10 ----
		label10.setText(TDSLanguageUtils.getMessage("panelGestionUsuarios.rol"));
		add(label10);
		label10.setBounds(20, 365, label10.getPreferredSize().width, 15);
		add(comboRol);
		comboRol.setBounds(110, 365, 115, comboRol.getPreferredSize().height);

		//---- label11 ----
		label11.setText(TDSLanguageUtils.getMessage("panelGestionUsuarios.email"));
		add(label11);
		label11.setBounds(new Rectangle(new Point(280, 375), label11.getPreferredSize()));
		add(textFieldEmail);
		textFieldEmail.setBounds(350, 370, 120, textFieldEmail.getPreferredSize().height);
		
		
		//---- label12 ----
		labelPass.setText(TDSLanguageUtils.getMessage("pantallaAccesoUsuario.pass"));
		add(labelPass);
		labelPass.setBounds(new Rectangle(new Point(275, 20), labelPass.getPreferredSize()));
		add(textPassword);
		textPassword.setBounds(350, 20, 120, textPassword.getPreferredSize().height);


		//======== scrollPane1 ========
		{
			scrollPane1.setViewportView(tableUsuarios);
		}
		add(scrollPane1);
		scrollPane1.setBounds(110, 425, 945, 200);

		//---- buttonBuscar ----
		buttonBuscar.setText(TDSLanguageUtils.getMessage("panelGestionUsuarios.buscar.boton"));
		buttonBuscar.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				buttonBuscarActionPerformed(e);
			}
		});
		add(buttonBuscar);
		buttonBuscar.setBounds(new Rectangle(new Point(430, 650), buttonBuscar.getPreferredSize()));

		//---- buttonBorrar ----
		buttonBorrar.setText(TDSLanguageUtils.getMessage("panelGestionUsuarios.borrar"));
		buttonBorrar.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				buttonBorrarActionPerformed(e);
			}
		});
		add(buttonBorrar);
		buttonBorrar.setBounds(new Rectangle(new Point(500, 650), buttonBorrar.getPreferredSize()));

		{ // compute preferred size
			Dimension preferredSize = new Dimension();
			for(int i = 0; i < getComponentCount(); i++) {
				Rectangle bounds = getComponent(i).getBounds();
				preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
				preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
			}
			Insets insets = getInsets();
			preferredSize.width += insets.right;
			preferredSize.height += insets.bottom;
			setMinimumSize(preferredSize);
			setPreferredSize(preferredSize);
		}
		
		//---- buttonActualizar ----
		buttonActualizar.setText(TDSLanguageUtils.getMessage("panelGestionUsuarios.actualizar"));
		buttonActualizar.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				buttonActualizarActionPerformed(e);
			}
		});
		add(buttonActualizar);
		buttonActualizar.setBounds(new Rectangle(new Point(610, 650), buttonActualizar.getPreferredSize()));

		{ // compute preferred size
			Dimension preferredSize = new Dimension();
			for(int i = 0; i < getComponentCount(); i++) {
				Rectangle bounds = getComponent(i).getBounds();
				preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
				preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
			}
			Insets insets = getInsets();
			preferredSize.width += insets.right;
			preferredSize.height += insets.bottom;
			setMinimumSize(preferredSize);
			setPreferredSize(preferredSize);
		}
	}

	

	protected void rellenarDatos(int fila) {
		Utils.clearPanel(this);
		if(tableModel.getValueAt(fila,0)!=null)
			this.textFieldDNI.setText(tableModel.getValueAt(fila,0).toString());
		if(tableModel.getValueAt(fila,2)!=null)
			this.textNombre.setText(tableModel.getValueAt(fila,2).toString());
		if(tableModel.getValueAt(fila,3)!=null)
			this.textApellido1.setText(tableModel.getValueAt(fila,3).toString());
		if(tableModel.getValueAt(fila,4)!=null)
			this.textFieldApellido2.setText(tableModel.getValueAt(fila,4).toString());
		if(tableModel.getValueAt(fila,5)!=null)
			this.textFieldCompania.setText(tableModel.getValueAt(fila,5).toString());
		if(tableModel.getValueAt(fila,6)!=null)
			this.textFieldDireccion.setText(tableModel.getValueAt(fila,6).toString());
		if(tableModel.getValueAt(fila,7)!=null)
			this.textFieldCodigoPostal.setText(tableModel.getValueAt(fila,7).toString());
		if(tableModel.getValueAt(fila,8)!=null)
			this.textFieldCiudad.setText(tableModel.getValueAt(fila,8).toString());
		if(tableModel.getValueAt(fila,9)!=null)
			this.textFieldTelefono.setText(tableModel.getValueAt(fila,9).toString());
		if(tableModel.getValueAt(fila,10)!=null)
			this.textFieldTelefonoMovil.setText(tableModel.getValueAt(fila,10).toString());
		if(tableModel.getValueAt(fila,11)!=null)
			this.comboRol.setSelectedIndex((Integer) tableModel.getValueAt(fila,11));
	}

	private void rellenarComboRoles(JComboBox comboRol2) {
		this.roles= new Hashtable<String, Integer>();
		List<Rol> roles=new LinkedList<Rol>();
		try {
			roles=servicios.getRoles();
			for (Iterator<Rol> iterator = roles.iterator(); iterator.hasNext();) {
				Rol rol = (Rol) iterator.next();
				comboRol.addItem(rol.getDescripcion());
				this.roles.put(rol.getDescripcion(), rol.getId());
			}
		} catch (RemoteException exception) {
			exception.printStackTrace();
		}
	}

	private Hashtable<String, Integer> roles;
	private JTextField textNombre;
	private JTextField textApellido1;
	private JLabel label1;
	private JLabel label2;
	private JTextField textFieldApellido2;
	private JLabel label3;
	private JTextField textFieldDNI;
	private JLabel label4;
	private JTextField textFieldCompania;
	private JLabel label5;
	private JTextField textFieldDireccion;
	private JLabel label6;
	private JTextField textFieldCodigoPostal;
	private JLabel label7;
	private JTextField textFieldCiudad;
	private JLabel label8;
	private JTextField textFieldTelefono;
	private JLabel label9;
	private JTextField textFieldTelefonoMovil;
	private JLabel label10;
	private JComboBox comboRol;
	private JLabel label11;
	private JTextField textFieldEmail;
	private JScrollPane scrollPane1;
	private JTable tableUsuarios;
	private JButton buttonBuscar;
	private JButton buttonBorrar;
	private JButton buttonActualizar;
	private JPasswordField textPassword;
	private JLabel labelPass;
	private EAulasTableModel tableModel;
}
